﻿using DingTalk.Common;
using DingTalk.Common.Mongodb;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DingWeb.Controllers
{
    /// <summary>
    /// 日志数据库
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MongodbController : ControllerBase
    {
        MongodbHost host = new MongodbHost();

        /// <summary>
        /// 构造函数
        /// </summary>
        public MongodbController()
        {
            host = new MongodbHost()
            {
                Connection = AppConfigurtaionHelper.Configuration["Mongodb:Connection"],//链接字符串
                DataBase = AppConfigurtaionHelper.Configuration["Mongodb:DataBase"],//库名
                Table = "t_user"//表名
            };
        }
        /// <summary>
        ///主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tb">表名，可以为空</param>
        /// <param name="field"></param>
        /// <returns></returns>      
        [HttpPost]
        public async Task<dynamic> GetById(string id, string tb, string[] field = null)
        {
            if (!string.IsNullOrWhiteSpace(tb))
            {
                host.Table = tb;
            }
            return await MongoDBService.FindOneAsync(host, id, field);
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="obj">任意类型数据集</param>
        /// <param name="tb">表名，可以为空</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> Insert(string data, string tb)
        {
            if (data == null)
            {
                return false;
            }

            if (!string.IsNullOrWhiteSpace(tb))
            {
                host.Table = tb;
            }

            object obj = new
            {
                key = "111",
                name = "2222"
            };

            //Dictionary<string, string> obj = new Dictionary<string, string>();
            //obj.Add("key", "111");
            //obj.Add("name", "22333");
            //var obj = JsonConvert.DeserializeObject<dynamic>(data);
            //object obj2 = JsonHelper.ParseJSON<dynamic>(data);


            //var json = "{\"key\":\"value1\",\"keyX\":{\"key\":\"value2\",\"keyX\":[{\"key\":\"value3\"},{\"key\":\"value4\"}],\"keyXX\":[\"value5\",\"value6\"]},\"keyXX\":[[{\"key\":\"value7\"},{\"key\":\"value8\"}],[\"value9\",\"value10\"]]}";
            //var jToken = JToken.Parse(json);

            //var dic1 = new Dictionary<string, object>();
            //var dic2 = new Dictionary<string, object>();
            //dic1 = JsonHelperExtension.GetDictionary(dic1, "S", jToken, null, 0);
            //dic2 = JsonHelperExtension.GetDictionary("S", jToken, dic2, -2);

            string json = "{Id:1,Name:\"刘备3333\",Age:\"223332\"}";
            Dictionary<string, string> list = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
            return await MongoDBService.AddAsync(host, obj);
        }
        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="tb">表名，可以为空</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> InsertAll(string data, string tb)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                return false;
            }
            if (!string.IsNullOrWhiteSpace(tb))
            {
                host.Table = tb;
            }

            List<object> obj = JsonHelper.ParseJSON<List<object>>(data);
            return await MongoDBService.InsertManyAsync(host, obj);
        }
        /// <summary>
        /// 改
        /// </summary>
        /// <param name="t"></param>
        /// <param name="id"></param>
        /// <param name="tb">表名，可以为空</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<dynamic> Update(string data, string id, string tb)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                return "更新内容不能为空";
            }

            if (string.IsNullOrWhiteSpace(id))
            {
                return "id 不能为空";
            }
            if (!string.IsNullOrWhiteSpace(tb))
            {
                host.Table = tb;
            }
            object obj = JsonHelper.ParseJSON<object>(data);
            return await MongoDBService.UpdateAsync(host, obj, id);
        }
        /// <summary>
        /// 删
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tb">表名，可以为空</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<dynamic> Delete(string id, string tb)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return "id 不能为空";
            }
            if (!string.IsNullOrWhiteSpace(tb))
            {
                host.Table = tb;
            }
            return await MongoDBService.DeleteAsync(host, id);
        }
        /// <summary>
        /// 查询列表，不分页
        /// </summary>
        /// <param name="tb">表名，可以为空</param>
        /// <param name="filter"></param>
        /// <param name="field"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<dynamic>> FindListAsync(string tb)
        {
            if (!string.IsNullOrWhiteSpace(tb))
            {
                host.Table = tb;
            }
            FilterDefinition<dynamic> filter = null;
            string[] field = null;
            SortDefinition<dynamic> sort = null;
            return await MongoDBService.FindListAsync(host, filter, field, sort);
        }
        /// <summary>
        /// 查询列表,分页
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="filter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="field"></param>
        /// <param name="sort"></param>
        /// <returns></returns>         
        [HttpGet]
        public async Task<List<dynamic>> FindListByPageAsync(string tb, int pageIndex, int pageSize = 15)
        {
            if (!string.IsNullOrWhiteSpace(tb))
            {
                host.Table = tb;
            }
            FilterDefinition<dynamic> filter = null;
            string[] field = null;
            SortDefinition<dynamic> sort = null;
            return await MongoDBService.FindListByPageAsync(host, filter, pageIndex, pageSize, field, sort);
        }

        //static dynamic ConvertJson(string json)
        //{              
        //    JavaScriptSerializer jss = new JavaScriptSerializer();
        //    jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); dynamic dy = jss.Deserialize(json, typeof(object)) as dynamic;
        //    return dy;
        //}
        //查
        //public static string SELECT(MongodbHost Host, string name)
        //{
        //    //var filter = Builders<object>.Filter.Empty;//无查询条件用这个

        //    //根据条件查询集合
        //    var time = DateTime.Now;
        //    var list = new List<FilterDefinition<object>>();
        //    list.Add(Builders<object>.Filter.Lt("createdate", time.AddDays(30)));
        //    list.Add(Builders<object>.Filter.Gt("createdate", time.AddDays(-30)));

        //    if (!string.IsNullOrEmpty(name) && !string.IsNullOrWhiteSpace(name))//模糊查询
        //    {
        //        string p = name == null ? $".*{Regex.Escape("")}.*" : $".*{Regex.Escape(name)}.*";
        //        list.Add(Builders<object>.Filter.Regex("name", new BsonRegularExpression(new Regex(p, RegexOptions.IgnoreCase))));
        //    }

        //    var filter = Builders<object>.Filter.And(list);
        //    //2.查询字段
        //    var field = new[] { "_id", "name", "password", "age", "phone" };//_id是mongo自带的主键  , "createdate" 
        //    //3.排序字段
        //    var sort = Builders<object>.Sort.Descending("createdate");

        //    var res = MongodbRepository<object>.FindList(Host, filter, field, sort);
        //    string json = JsonConvert.SerializeObject(res);
        //    return json;
        //}
    }
}
